package main

import "fmt"

// 函数式编程，闭包应用-累加器
// 闭包：函数体->局部变量+自由变量
func adder() func(int) int { //函数体
	sum := 0                 //sum为自由变量，函数体全局变量，连接构成树
	return func(v int) int { //v为局部变量
		sum += v
		return sum
	}
}

// 正统无变量函数式编程-累加器
type iAdder func(int) (int, iAdder) //递归写法

func adder2(base int) iAdder {
	return func(v int) (int, iAdder) {
		return base + v, adder2(base + v)
	}
}

func main() {
	a := adder() //is trivial and also works.
	a2 := adder2(0)
	for i := 0; i < 10; i++ {
		var s int
		s, a2 = a2(i)
		fmt.Printf("0 + 1 + ... + %d = %d\n",
			i, s)
		fmt.Printf("0 + 1 + ... + %d = %d\n",
			i, a(i))
	}
}
